package factory;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

public class RedisDistributionLock implements DistributionLock{
	
	private RedisTemplate<Object, Object> redisTemplate;
	private String lockKey = null;
	private String lockValue = UUID.randomUUID().toString();
	/**
	 * 加锁超时时间，单位毫秒， 即：加锁时间内执行完操作，如果未完成会有并发现象  
	 */
	private long lock_timeout = 5*1000;  
    
	/**
	 * 构造函数
	 * @param redisTemplate
	 * @param lockKey
	 * @param lock_timeout
	 */
	
	public RedisDistributionLock(RedisTemplate<Object, Object> redisTemplate,String lockKey){
		this.redisTemplate = redisTemplate;
		this.lockKey = lockKey;
	}
	
	public RedisDistributionLock(RedisTemplate<Object, Object> redisTemplate,String lockKey,long lock_timeout){
		this.redisTemplate = redisTemplate;
		this.lockKey = lockKey;
		this.lock_timeout=lock_timeout;
	}
	
	/**
	 * 加锁 (加不到锁一直循环直到加上锁)
	 */
	@Override
	public void acquire() {
		while(true){
			if(redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue)){
				redisTemplate.expire(lockKey, lock_timeout, TimeUnit.MILLISECONDS);
				System.out.println("线程"+Thread.currentThread().getName()+"获得锁");
				break;
			}else{
				try{
					System.out.println("出现锁等待");
					Thread.sleep(100);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 解锁
	 */
	@Override
	public void release() {
		if(redisTemplate.opsForValue().get(lockKey).equals(lockValue)){
			System.out.println("线程"+Thread.currentThread().getName()+"释放锁");
			redisTemplate.delete(lockKey);
		}
	}
}
